﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.SqlTypes;
using System.Data.Common;

namespace ARPrimitiveType.Model
{
	public class CompanyType : NHibernate.Type.PrimitiveType
	{
		public static readonly CompanyType Software = new CompanyType() { Description = "Software", Value = 1 };
		public static readonly CompanyType Manufacturing = new CompanyType() { Description = "Manufacturing", Value = 2 };
		public static readonly CompanyType Insurance = new CompanyType() { Description = "Insurance", Value = 3 };

		private static readonly CompanyType[] AllTypes = new CompanyType[] { Software, Manufacturing, Insurance };

		public string Description { get; set; }
		public int Value { get; set; }

		public override string ToString()
		{
			return this.Description;
		}

		public CompanyType()
			: base(SqlTypeFactory.Int32)
		{
		}

		public override object DefaultValue
		{
			get { return CompanyType.Software; }
		}

		public override string ObjectToSQLString(object value, NHibernate.Dialect.Dialect dialect)
		{
			CompanyType type = value as CompanyType;
			return type.Value.ToString();
		}

		public override Type PrimitiveClass
		{
			get { return typeof(Int32); }
		}

		public override object FromStringValue(string xml)
		{
			return GetCompanyType(xml);
		}

		public override object Get(System.Data.IDataReader rs, string name)
		{
			return GetCompanyType(rs[name]);
		}

		public override object Get(System.Data.IDataReader rs, int index)
		{
			return GetCompanyType(rs[index]);
		}

		private object GetCompanyType(object val)
		{
			if (val == null)
			{
				return DefaultValue;
			}

			int v = Int32.Parse(val.ToString());
			return AllTypes.First(x => x.Value == v);
		}

		public override void Set(System.Data.IDbCommand cmd, object value, int index)
		{
			CompanyType type = value as CompanyType;
			DbParameter param = cmd.Parameters[index] as DbParameter;
			param.Value = type.Value;
		}

		public override string Name
		{
			get { return "CompanyType"; }
		}

		public override Type ReturnedClass
		{
			get { return typeof(CompanyType); }
		}
	}
}
